<template>
  <el-card style="max-width: 100%">
    <template #header>
      <div class="card-header">
        <span>用户列表</span>
      </div>
    </template>
    <!-- 用户列表 -->
    <el-table :data="userData" style="width: 100%">
      <el-table-column label="编号" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.$index+1 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
const userData = ref([]);
//获取用户列表
const getUserData = () => {
  axios.get("http://localhost:3000/users").then((res) => {
    console.log(res);
    userData.value = res.data;
  });
};
//删除用户
const handleDelete = (id) => {
  console.log(id);
  axios
    .delete("http://localhost:3000/users/" + id)
    .then((res) => {
      console.log(res);
      if (res.statusText == "OK") {
        ElMessage({
          message: "删除成功！",
          type: "success",
        });
        getUserData();
      } else {
        ElMessage.error("删除失败，请联系管理员");
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
onMounted(() => {
  getUserData();
});
</script>

<style>
</style>